<?php
# coding by davis
function call_mis_api(& $data){
    if(isset($data['callback_data']['mis_xml_urls']))
    {
        $ret = true;
        foreach($data['callback_data']['mis_xml_urls'] as $url)
        {
            if(file_get_contents($url)){
                continue;
            }
            else{
                $request = new HttpRequest();
                $request->setUrl($url);
                $request->send();
                if($request->getResponseCode()!=200) {
                    throw new Exception("MIS API($url) Error: MIS Return Code => ".$request->getResponseCode());
                }

                $info = $request->getResponseBody();
                if(preg_match('#<ERROR>#i',$info)) 
                {
                    throw new Exception("MIS API($url) Return Error:\n".$info); //return false;
                }
                $ret = false;
            }
        }
        return $ret;
    }
    else return true;
}

# coding by vanni
function merge_data_and_update_db3(& $data,$db){
	$rs = array();
	$replace_item = array(
		'Video'     => array('vi_id'        => 'vi_ids',   'image_id'        => 'ii_ids'),
		'Programme' => array('banner_image' => 'ii_ids',   'key_art_image'   => 'ii_ids'),
		'Personage' => array('head_image'   => 'ii_ids',   'full_body_image' => 'ii_ids', 'other_image' => 'ii_ids'),
		'Chapter'   => array('image_id'     => 'ii_ids'),
		'Image'     => array('ii_id'        => 'ii_ids'),
		'FolderItemImage' => array('ii_id'  => 'ii_ids'),
		'FolderItemVideo' => array('vi_id'  => 'vi_ids','image_id'=>'ii_ids'),
	);

	$key_art_size = '975x200';
	$banner_size  = '225x95';
	$full_body_size = '200x500';

	#echo print_r(array_keys($data['ii_ids']),1) , print_r(array_keys($data['vi_ids']),1);

	foreach($data['callback_data']['db3']['update'] as $item){
		if(isset($replace_item[$item['type']])){
			#echo "befer\n",print_r($item,1);
			$vi_id = ('Video'==$item['type']) ? ($item['data']['vi_id']) : 0;
			foreach($replace_item[$item['type']] as $field=>$source){  // source : ii_ids or vi_ids

				if('key_art_image' == $field){ // only programme:key_art_image is array
					$key_art_img_data = array();
					foreach($item['data'][$field] as $key_art_img_id){
						if(isset($data['ii_ids'][$key_art_img_id][$key_art_size])){
							$key_art_img_data = array(
								$key_art_size => $data['ii_ids'][$key_art_img_id][$key_art_size],
								'id' => $key_art_img_id
							);
							break;
						}
					}
					$item['data'][$field] = $key_art_img_data;
				}else{
					if($item['data'][$field]){ // is not 0 , '' or null : 有时从DB2拿到的数据没有ii_id
						$the_id = $item['data'][$field];
						
						#从 viiiProcess 传来的数组中能获得到数据
						if(isset($data[$source][$the_id])){
							$item['data'][$field] = $data[$source][$the_id];
							if('ii_ids' == $source)
							{
								$item['data'][$field]['ii_id'] = $the_id;
							}
						}else{
							# viiiProcess 没有给我们想要的数据
							# Send an error mail to Keith?
							$mail_str  = "\n\n\n=====================================================================\n";
							$mail_str .= "=== Notice: not found $source id {$item['data'][$field]} form viiiProcess ===\n";
							$mail_str .= "=====================================================================\n\n\n";
							echo $mail_str;
							mail(CommonUtils::getAdminMail(),
								"Notice: not found $source id {$item['data'][$field]} form viiiProcess!!!",
								$mail_str."$source data is:\n".print_r($data[$source],1)
							);
						}
					}
				}
			}
			if($vi_id){ //if('Video'==$item['type'] && $vi_id){
				$item['data']['duration']   = $data['vi_ids'][$vi_id]['duration'];
				$item['data']['breakpoint'] = $data['vi_ids'][$vi_id]['breakpoint'];
			}

			# for bug 6733
			if($item['type'] == 'Programme'){ // banner_image
				if(!isset($item['data']['banner_image'][$banner_size])){
					$item['data']['banner_image'] = array();
				}else{
					$item['data']['banner_image'] = array(
						$banner_size => $item['data']['banner_image'][$banner_size],
						'id' => $item['data']['banner_image']['ii_id']
					);
				}
			}elseif($item['type'] == 'Personage'){ //full_body_image; head_image:unlimit
				if(!isset($item['data']['full_body_image'][$full_body_size])){
					$item['data']['full_body_image'] = array();
				}else{
					$item['data']['full_body_image'] = array(
						'id'=>$item['data']['full_body_image']['ii_id'],
						'origin'=>$item['data']['full_body_image'][$full_body_size]
					);
				}
				if(is_array($item['data']['head_image']) && $item['data']['head_image']){ // is 0, '' or null
					$item['data']['head_image']['id'] = $item['data']['head_image']['ii_id'];
					unset($item['data']['head_image']['ii_id']);
				}else{
					$item['data']['head_image'] = array();
				}
			}
		}
		#echo "after\n",print_r($item,1);
		$rs[] = $item;
	}

	$is_premium = ('p_' == substr($data['action'],0,2));
	try{
		update_db3($rs,$db,$is_premium);
	}catch(Exception $e){
		file_put_contents("/tmp/vanni_{$data['action']}_debug.log",print_r($e,1));
		file_put_contents("/tmp/vanni_{$data['action']}_db3.log",print_r($rs,1));
		file_put_contents("/tmp/vanni_{$data['action']}_data.log",print_r($data,1));
		throw $e;
	}
}

function update_db3($db3_data, $rf, $is_premium){
	$class_prefix = $is_premium ? '\DB3\P_' : '\DB3\\';
	$table_prefix = $is_premium ? 'p_' : '';
	$notification = array();

	foreach ($db3_data as $item) {
		if (!isset($item['type']) || !isset($item['data'])) {
			throw new Exception("Invalid message format");
		}

		$type = $class_prefix.$item['type'];
		$data = $item['data'];

		switch ($type) {
		case $class_prefix.'ProgrammeCategory':
			$key = array(
				'programme_id' =>$data['programme_id'],
				'category_id_0'=>$data['category_id_0'],
				'category_id_1'=>$data['category_id_1']
			);
			$object = array_shift($rf->find($type, 'programme_id=? AND category_id_0=? AND category_id_1=?', $key));
			break;

		case $class_prefix.'ProgrammeChannel':
			$key = array(
				'network_code'=>$data['network_code'],
				'main_category_id'=>$data['main_category_id'],
				'programme_id'=>$data['programme_id']						
			);
			$object = array_shift($rf->find($type, 'network_code=? AND main_category_id=? AND programme_id=?', $key));
			break;

		case $class_prefix.'FolderItem':
			$key = array(
				'folder_id'=>$data['folder_id'],
				'programme_id'=>$data['programme_id'],
				'item_type'=>$data['item_type'],
				'item_id'=>$data['item_id']
			);
			$object = array_shift($rf->find($type, 'folder_id=? AND programme_id=? AND item_type=? AND item_id=?', $key));
			break;

		case $class_prefix.'FolderItemImage':
		case $class_prefix.'FolderItemVideo':
			$key = array(
				'folder_id'=>$data['folder_id'],
				'programme_id'=>$data['programme_id'],
				'id'=>$data['id']
			);
			$object = array_shift($rf->find($type, 'folder_id=? AND programme_id=? AND id=?', $key));
			break;

		case $class_prefix.'Info':
			$key = array(
				'info_id'=>$data['info_id'],
				'info_type_id'=>$data['info_type_id']
			);
			$object = array_shift($rf->find($type,'info_id=? AND info_type_id=?',$key));
			break;

		default:
			$key = $data['id'];
			$object = $rf->findInstance($type, $data['id']);
		}

		$item['key'] =  is_array($key) ? implode(',',$key) : $key;

		if (!$object) {
			switch ($type) {
			case $class_prefix.'Programme':
			case $class_prefix.'Category':
			case $class_prefix.'Chapter':
			case $class_prefix.'Episode':
			case $class_prefix.'Folder':
			case $class_prefix.'FolderItem':
			case $class_prefix.'FolderItemImage':
			case $class_prefix.'FolderItemVideo':
			case $class_prefix.'Image':
			case $class_prefix.'Personage':
			case $class_prefix.'ProgrammeCategory':
			case $class_prefix.'ProgrammeChannel':
			case $class_prefix.'Video':
			case $class_prefix.'Info':
				$object = new $type();
				break;
			default:
				throw new Exception("Unknown type $type");
			}
		}

		foreach ($data as $k => $v) {
			if (is_array($v) || is_object($v)) {
				$object->$k = json_encode($v);
			} else {
				$object->$k = is_null($v) ? '' : $v;
			}
		}

		$fields = is_array($key) ? array_keys($key) : array('id');
		#echo " DEBUG:\n",$object->getTableName(),"; IS NEW:",$object->isNew(),';',print_r($key,1);

		$rf->save_by_fields($object,$fields);
		echo "Received Object $type => [{$item['key']}].\n";
		array_push($notification,array('action'=>'update','object'=>$item['type'],'id'=>$item['key']));			
	}

	return true;
	# break for test

	$config = ConfigReaderFactory::getInstance()->getConfigReader(AC::CONFIG_MQ)->getConfig();
	$consumerConfig = $config->xpath("/config/consumer[@name='PMSWebServiceNotification'or@name='PMSWebServiceNotification.PP'or@name='PMSWebServiceNotification.EPG'or@name='PMSWebServiceNotification.Search']");
	foreach ( $consumerConfig as $idx => $consumer ) {
		echo $consumer ;
		MessageHelper::sendMessage($consumer->broker, $consumer->queue, $notification);
	}
}



function update_db1(& $data,$db,$status){
	$audit_log_id = $data['callback_data']['audit_log_id'];
	$type         = $data['action'];
	$is_unpublish = (strpos($type,'unpublish') !== false);

	if(strtolower(substr($type,0,2)) == 'p_'){
		if($is_unpublish){
			if($status){
				$action = AC::LOG_OP_PREMIUM_UNPUBLISH;
				$status = AC::STATUS_UNPUBLISH_PREMIUM;
				$remark = "Unpublish Premium Successful.";
			}else{
				$action = AC::LOG_OP_PREMIUM_UNPUBLISH_FAILED;
				$status = AC::STATUS_LOG_FAILED_PREMIUM;
				$remark = "Unpublish Premium Failed.";
			}
		}else{
			if($status){
				$action = AC::LOG_OP_PREMIUM_PUBLISH;
				$status = AC::STATUS_PUBLISH_PREMIUM;
				$remark = "Proofread Premium Successful.";
			}else{
				$action = AC::LOG_OP_PREMIUM_PUBLISH_FAILED;
				$status = AC::STATUS_LOG_FAILED_PREMIUM;
				$remark = "Proofread Premium Failed.";
			}
		}
	}else{
		if($is_unpublish){
			if($status){
				$action = AC::LOG_OP_UNPUBLISH;
				$status = AC::STATUS_UNPUBLISH;
				$remark = "Unpublish Successful.";
			}else{
				$action = AC::LOG_OP_UNPUBLISH_FAILED;
				$status = AC::STATUS_LOG_FAILED;
				$remark = "Unpublish Failed.";
			}
		}else{
			if($status){
				$action = AC::LOG_OP_PUBLISH;
				$status = AC::STATUS_PUBLISH;
				$remark = "Proofread Successful.";
			}else{
				$action = AC::LOG_OP_PUBLISH_FAILED;
				$status = AC::STATUS_LOG_FAILED;
				$remark = "Proofread Failed.";
			}
		}
	}

	$sql = 'update audit_log set action=?, remarks=? where id=?';
	$ps  = $db->getDbHandle()->prepare($sql);
	echo "Update DB1 audit_log status[$sql] => $action, $remark, $audit_log_id\n";
	$ps->execute(array($action, $remark, $audit_log_id));

	$sql = 'update publish_log set status=?, action=?, remarks=? where id=?';
	$ps  = $db->getDbHandle()->prepare($sql);
	
	foreach($data['callback_data']['publish_log_ids'] as $ids){
		foreach($ids as $id){
			echo "Update DB1 publish_log status[$sql] => $status, $action, $remark, $id\n";
			$rs = $ps->execute(array($status, $action, $remark, $id));
		}
	}
}

function delete_db3_data(& $data,$rf){
	if(empty($data['callback_data']['db3']['delete'])) return;
	#echo "Need to delete items:\n",print_r($data['callback_data']['db3']['delete'],1);

	$is_premium = ('p_' == substr($data['action'],0,2));
	$class_prefix = $is_premium ? '\DB3\P_' : '\DB3\\';
	$table_prefix = $is_premium ? 'p_' : '';

	$sql = $pam = array();
	$folderItemTypes = array('image'=>2,'video'=>1);
	foreach($data['callback_data']['db3']['delete'] as $row)/*{{{*/
	{
		$table = $row['type'];
		$keys  = $row['keys'];
		if(isset($keys['id'])){
			echo "Delete Table[",$class_prefix,$table,"], id = ",$keys['id']."\n";
			$rf->deleteInstance($class_prefix.$table, $keys['id']);
		}

		switch ($table) {
		case 'Programme':
		case 'Personage':
		case 'Category':
		case 'Chapter':
		case 'FolderItemImage':
		case 'FolderItemVideo':
		case 'ProgrammeCategory':
		case 'ProgrammeChannel':
			# needn't update or delete 
			break;
		case 'Episode':
			#$sql[] = 'update `'.$table_prefix.'folder_item-video` set episode_id=0 where episode_id=?';
			#$sql[] = 'update `'.$table_prefix.'video` set episode_id=0 where episode_id=?';
			#$sql[] = 'update `'.$table_prefix.'chapter` set episode_id=0 where episode_id=?';
			#$pam[] = array($keys['id']);
			#$pam[] = array($keys['id']);
			#$pam[] = array($keys['id']);
			break;
		case 'Folder':
			$sql[] = 'delete from `'.$table_prefix.'folder_item-image` where folder_id=?';
			$sql[] = 'delete from `'.$table_prefix.'folder_item-video` where folder_id=?';
			$sql[] = 'delete from `'.$table_prefix.'folder_item` where folder_id=?';
			$pam[] = array($keys['id']);
			$pam[] = array($keys['id']);
			$pam[] = array($keys['id']);
			break;
		case 'Image':
			$sql[] = 'delete from `'.$table_prefix.'folder_item-image` where id=?';
			$sql[] = 'delete from `'.$table_prefix.'folder_item` where item_id=? and item_type=?';
			$pam[] = array($keys['id']);
			$pam[] = array($keys['id'],$folderItemTypes['image']);
			break;
		case 'Video':
			$sql[] = 'delete from `'.$table_prefix.'folder_item-video` where id=?';
			$sql[] = 'delete from `'.$table_prefix.'folder_item` where item_id=? and item_type=?';
			$sql[] = 'delete from `'.$table_prefix.'chapter` where video_id=?';
			$pam[] = array($keys['id']);
			$pam[] = array($keys['id'],$folderItemTypes['video']);
			$pam[] = array($keys['id']);
			break;
		case 'FolderItem':
			$sql[] = 'delete from `'.$table_prefix.'folder_item` where folder_id=? and item_id=? and item_type=?';
			$pam[] = array($keys['folder_id'],$keys['item_id'],$keys['item_type']);

			# for bug 7680,7681
			if($keys['item_type']==2){// image
				$sql[] = 'delete from `'.$table_prefix.'folder_item-image` where folder_id=? and id=?';
			}else{
				$sql[] = 'delete from `'.$table_prefix.'folder_item-video` where folder_id=? and id=?';
			}
			$pam[] = array($keys['folder_id'],$keys['item_id']);
			break;
		case 'Info':
			$sql[] = 'delete from `'.$table_prefix.'info` where info_type_id=? and info_id=?';
			$pam[] = array($keys['info_type_id'],$keys['info_id']);
			break;
		}
	}/*}}}*/

	foreach($sql as $i=>$s){
		echo "\tDelete related data[$s] => ",implode(',',$pam[$i])."\n";
		$ps  = $rf->getDbHandle()->prepare($s);
		$ps->execute($pam[$i]);
	}
	return true;
}

function delete_change_log(& $data){
	if(empty($data['callback_data']['change_log'])) return true;

	$db = CommonUtils::getMongoDB();
	
	foreach($data['callback_data']['change_log'] as $row){
		$query = array(
			'type'=>$row['type'],
			'keys'=>$row['keys'],
			'is_publish'=>1,
		);
		$db->remove($query);
	}
	return true;
}

function reset_change_log( & $data){
	if(empty($data['callback_data']['change_log'])) return true;

	$db = CommonUtils::getMongoDB();
	
	foreach($data['callback_data']['change_log'] as $row){
		$query = array(
			'type'=>$row['type'],
			'keys'=>$row['keys'],
			'is_publish'=>1,
		);
		$db->update($query,array('$set'=>array('is_publish'=>0)));
	}
	return true;
}
